import datetime
import uuid

from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from web.forms.account import *  # RegisterModelForm, SendSmsForm, LoginSMSForm


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    elif request.method == 'POST':
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            # 验证通过了，所有提交的数据都没问题
            # 在数据库中创建这个新用户
            # 下面这个.save()相当于：
            # instance = models.UserInfo.objects.create(**form.cleaned_data)
            instance = form.save()  # 还能自动剔除不合适的字段，如code。这个instance应该就是这个用户对象

            # 创建交易记录
            # 方式一：用户注册时自动增加一个免费的交易记录
            price_policy_obj = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
            models.Transaction.objects.create(
                status=2,
                order=str(uuid.uuid4()),  # uuid库用来创建一个随机字符串，以此作为订单号
                user=instance,
                price_policy=price_policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()
            )

            return JsonResponse({'status': True, 'data': '/login/'})
        return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    # 传递进去的data有手机号和tpl两个值，但是由于我们的form表单只定义了手机号字段，所以这里只对手机号进行校验
    form = SendSmsForm(request, data=request.GET)

    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'web/login_sms.html', {'form': form})
    elif request.method == 'POST':
        form = LoginSMSForm(request.POST)
        if form.is_valid():
            user_object = form.cleaned_data['mobile_phone']
            request.session['user_id'] = user_object.id
            # request.session['user_name'] = user_object.username
            request.session.set_expiry(60 * 60 * 24 * 30)

            return JsonResponse({'status': True, 'data': '/index/'})
        return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    elif request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            # 前面的form校验成功，密码已经加密，验证码已通过
            usn = form.cleaned_data['username']
            pwd = form.cleaned_data['password']
            # usr_obj = models.UserInfo.objects.filter(username=usn, password=pwd).first()
            # （用户名相等或手机号相等）且（密码正确）---> Q
            usr_obj = models.UserInfo.objects.filter(Q(username=usn) | Q(mobile_phone=usn)).filter(password=pwd).first()

            if usr_obj:
                # 这里表示登录成功了
                request.session['user_id'] = usr_obj.id
                request.session.set_expiry(60 * 60 * 24 * 30)
                return redirect('index')
            form.add_error('password', '用户名或密码错误')
        return render(request, 'web/login.html', {'form': form})


def image_code(request):
    from utils.image_code import check_code
    from io import BytesIO

    image_object, code = check_code()
    request.session['img_code'] = code
    request.session.set_expiry(90)  # 主动修改session过期时间
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('index')